﻿using System;
using System.ComponentModel;
using System.Device.Location;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using ChinaGeo;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;

namespace ChinaGeoTest
{
    public partial class MainPage : PhoneApplicationPage
    {
        GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(MainPage_BackKeyPress);
            myMap.Tap += new EventHandler<GestureEventArgs>(myMap_Tap);
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            watcher.Start();
            myMap.SetView(watcher.Position.Location, 14);
        }

        void MainPage_BackKeyPress(object sender, CancelEventArgs e)
        {
            ChinaGeoHelper.SaveCache();
        }

        void myMap_Tap(object sender, GestureEventArgs e)
        {
            var location = myMap.ViewportPointToLocation(e.GetPosition(myMap));
            ChinaGeoHelper.ChinaToEarth(location, m =>
            {
                textBlock.Text = string.Format("Earth: {0}\nChina: {1}\nIsEffected: {2}\nTimestamp: {3}", m.EarthGeo, m.ChinaGeo, m.IsEffected, m.Timestamp);
            });
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
        }

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            if (!e.Position.Location.IsUnknown)
            {
                ChinaGeoHelper.EarthToChina(e.Position.Location, m =>
                {
                    textBlock.Text = string.Format("Earth: {0}\nChina: {1}\nIsEffected: {2}\nTimestamp: {3}", m.EarthGeo, m.ChinaGeo, m.IsEffected, m.Timestamp);
                });
            }
        }
    }
}